package org.oschina.helper.db.impl;

import java.util.List;

import org.oschina.Constants;
import org.oschina.helper.db.IDBHelper;
import org.oschina.util.JdbcTemplateUtil;
import org.oschina.util.ReflectUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import com.alibaba.druid.sql.SQLUtils;
import com.alibaba.druid.util.JdbcUtils;

@Component
public class DBHelperImpl implements IDBHelper {
	
	private final static Logger logger=LoggerFactory.getLogger(DBHelperImpl.class);
	
	@Autowired
	private JdbcTemplate jdbcTemplate;

	@Override
	public int[] batchUpdate(String sql, List<Object[]> args)
	{
		show_sql(sql);
		return JdbcTemplateUtil.batchUpdate(sql, args, jdbcTemplate);
	}

	@Override
	public List query(String sql, Object[] args, Class type)
	{
		show_sql(sql);
		return JdbcTemplateUtil.query(sql, args, type, jdbcTemplate);
	}

	@Override
	public Object queryForObject(String sql, Object[] args, Class type)
	{
		show_sql(sql);
		if(ReflectUtil.isBasic(type))
			return JdbcTemplateUtil.queryForObject(sql, args, type, jdbcTemplate);
		else
			return JdbcTemplateUtil.queryForBean(sql, args, type, jdbcTemplate);
	}

	@Override
	public long update(String sql, Object[] args)
	{
		show_sql(sql);
		return JdbcTemplateUtil.update(sql, args, jdbcTemplate);
	}
	
	/**
	 * 输出sql
	 * @param sql
	 */
	private void show_sql(String sql)
	{
		if(Constants.DB_SHOW_SQL)
			logger.info("\nshow_sql:\n{}",SQLUtils.format(sql,JdbcUtils.MYSQL));
	}

}